/* $RCSFile: ADNPage.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/ADNPage.cs $
 * $log$
 * Revision 19 2011/01/25 20:30:11  christian.surieux
 *   Move to framework 4
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Design;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Settings.Cache;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;

namespace AddonNice.UI
{

	#region Event classes, Delegates for Date, Filter and SortOrder

    /// <summary>
    /// Used when updating page content pressing add, update, save and update or delete button
    /// </summary>
    public class ADNPageEventArgs : EventArgs
	{
        public enum PgEventType : int { unknown = 0, Add, Update, Delete,SaveAndClose,AdminProp,Cancel, Custom };

        public PgEventType EvType       =   PgEventType.unknown;
		public bool Cancel              =   false;
        public bool FlushCache          =   true;
        public bool OverrideDemo        =   false;
		public bool RedirectOnSuccess   =   true;
		public EventArgs OrgEvent       =   null;
		public string RedirectUrl       =   string.Empty;

        public ADNPageEventArgs(PgEventType tp,EventArgs oe)
		{
            EvType              =   tp;
            OrgEvent            =   oe;
		}

        
        public ADNPageEventArgs(PgEventType tp,EventArgs oe,bool redirect,string urlRedirect)
		{
            EvType              =   tp;
            OrgEvent            =   oe;
            RedirectOnSuccess   =   redirect;
		    RedirectUrl         =   urlRedirect;
		}
	}
    
    public delegate void PageEventHandler(object sender,ADNPageEventArgs e);
    
    
    
    public class QueryDateChangedEventArgs : EventArgs
	{
		public DateTime OldTime;
		public DateTime NewTime;
		
		// constructor from a productID
		public QueryDateChangedEventArgs(DateTime wOldTime,DateTime wNewTime)
		{
			OldTime	=	wOldTime;
			NewTime	=	wNewTime;
		}
	}

	public delegate void QueryDateChangedEventHandler(QueryDateChangedEventArgs e);

	public class FilterChangedEventArgs : EventArgs
	{
		public string OldFilter;
		public string NewFilter;
		
		// constructor from a productID
		public FilterChangedEventArgs(string wOld,string wNew)
		{
			OldFilter	=	wOld;
			NewFilter	=	wNew;
		}
	}
	
	public delegate void FilterChangedEventHandler(FilterChangedEventArgs e);

	public class SortOrderChangedEventArgs : EventArgs
	{
		public string OldSortOrder;
		public string NewSortOrder;
		
		// constructor from a productID
		public SortOrderChangedEventArgs(string wOld,string wNew)
		{
			OldSortOrder	=	wOld;
			NewSortOrder	=	wNew;
		}
	}

	public delegate void SortOrderChangedEventHandler(SortOrderChangedEventArgs e);

	public class SortDirectionChangedEventArgs : EventArgs
	{
		public string OldSortDirection;
		public string NewSortDirection;
		
		// constructor from a productID
		public SortDirectionChangedEventArgs(string wOld,string wNew)
		{
			OldSortDirection	=	wOld;
			NewSortDirection	=	wNew;
		}
	}

	public delegate void SortDirectionChangedEventHandler(SortDirectionChangedEventArgs e);

	public class PageSizeChangedEventArgs : EventArgs
	{
		public int		OldPageSize;
		public int		NewPageSize;
		
		// constructor from a productID
		public PageSizeChangedEventArgs(int wOld,int wNew)
		{
			OldPageSize	=	wOld;
			NewPageSize	=	wNew;
		}
	}

	public delegate void PageSizeChangedEventHandler(PageSizeChangedEventArgs e);
	
	
	
	#endregion Delegates for Date, Query and Sort

    #region Tootip enum

    public enum TootipPos { Top = 0, Bottom };

    #endregion Tootip enum

    /// <summary>
	/// A template page useful for constructing custom edit pages for module settings.<br/>
	/// Encapsulates some common code including: moduleid, 
	/// portalSettings and settings, referrer redirection, edit permission, cancel event, etc.
	/// </summary>
	public class ADNPage : Page, IPostBackEventHandler
	{

        #region RadWindowManager
        RadWindowManager _WinManager    =   null;

        bool shouldRegisterConfirm      =   false;
        bool    _useRadConfirm          =   true;
        
        /// <summary>
        /// Use RadConfirm in place of browser confirm
        /// Default to true
        /// </summary>
        public bool useRadConfirm
        {
            get
            {
                return _useRadConfirm;
            }
            set
            {
                _useRadConfirm = value;
            }
        }
        
        
        string _RadWindowManagerName  =   "RadWindowManager1";
        public virtual string RadWindowManagerName
        {
            get
            {
                return _RadWindowManagerName;
            }
            set
            {
                _RadWindowManagerName =   value;
            }
        }

        /// <summary>
        /// Always load a RadWindowManager and add it to control collection in OnInit
        /// </summary>
        public RadWindowManager WinManager
        {
            get
            {
                if ( _WinManager == null )
                {
                    if (!string.IsNullOrEmpty(MasterPageFile) && Master != null)
                    {
                        _WinManager = (RadWindowManager)Master.FindControl(RadWindowManagerName);
                        if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage WinManager GET from MasterPageFile: {0}, found: {1}",
                                MasterPageFile,(_ToolTipManager != null) ), PageTraceSwitch.Sw.Info);
                    }
                    if (_WinManager == null)
                        _WinManager = (RadWindowManager) FindControl(RadWindowManagerName);
                   if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage WinManager GET found: {0}.",(_WinManager != null )),PageTraceSwitch.Sw.Info);
                }
                return _WinManager;
            }
            set
            {
                _WinManager = value;
               if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage WinManager SET ID: {0}.",_WinManager.ID),PageTraceSwitch.Sw.Info);
            }
        }
        
        #endregion RadWindowManager
        
        #region RadToolTipManager
        
        string _ToolTipManagerName  =   "RTTManager1";
        public virtual string ToolTipManagerName
        {
            get
            {
                return _ToolTipManagerName;
            }
            set
            {
                _ToolTipManagerName =   value;
            }
        }

        string _ToolTipManagerBottomName  =   "RTTManager2";
        public virtual string ToolTipManagerBottomName
        {
            get
            {
                return _ToolTipManagerBottomName;
            }
            set
            {
                _ToolTipManagerBottomName =   value;
            }
        }

        public bool HasToolTipManager
        {
            get
            {
                return ToolTipManager != null;
            }
        }
        
        public bool HasToolTipManagerBottom
        {
            get
            {
                return ToolTipManagerBottom != null;
            }
        }

        protected RadToolTipManager _ToolTipManager =   null;
        public virtual RadToolTipManager ToolTipManager
        {
            get
            {
                if (_ToolTipManager == null)
                {
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManager GET BEG ToolTipManagerName: {0}",ToolTipManagerName), PageTraceSwitch.Sw.Info);
                    if (!string.IsNullOrEmpty(MasterPageFile) && Master != null)
                    {
                        _ToolTipManager = (RadToolTipManager)Master.FindControl(ToolTipManagerName);
                        if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManager GET from MasterPageFile: {0}, found: {1}",
                                MasterPageFile,(_ToolTipManager != null) ), PageTraceSwitch.Sw.Info);
                    }
                    if (_ToolTipManager == null)
                        _ToolTipManager = (RadToolTipManager)FindControl(ToolTipManagerName);
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManager GET ToolTipManagerName: {0}, found: {1}",
                            ToolTipManagerName,(_ToolTipManager != null) ), PageTraceSwitch.Sw.Info);
                }
                return _ToolTipManager;
            }
        }

        protected RadToolTipManager _ToolTipManagerBottom =   null;
        public virtual RadToolTipManager ToolTipManagerBottom
        {
            get
            {
                if (_ToolTipManagerBottom == null)
                {
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManagerBottom GET BEG ToolTipManagerBottom: {0}",ToolTipManagerBottomName), PageTraceSwitch.Sw.Info);
                    if (!string.IsNullOrEmpty(MasterPageFile) && Master != null)
                    {
                        _ToolTipManagerBottom = (RadToolTipManager)Master.FindControl(ToolTipManagerBottomName);
                        if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManager GET from MasterPageFile: {0}, found: {1}",
                                MasterPageFile,(_ToolTipManagerBottom != null) ), PageTraceSwitch.Sw.Info);
                    }
                    if (_ToolTipManagerBottom == null)
                        _ToolTipManagerBottom = (RadToolTipManager)FindControl(ToolTipManagerBottomName);
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ToolTipManagerBottom GET ToolTipManagerBottomName: {0}, found: {1}",
                            ToolTipManagerBottomName,(_ToolTipManagerBottom != null) ), PageTraceSwitch.Sw.Info);
                }
                return _ToolTipManagerBottom;
            }
        }

        public void AddToolTipTarget(string CtlName, bool isClientID,TootipPos Pos)
        {
            if ( (Pos == TootipPos.Bottom) && ( ToolTipManagerBottom != null) )
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage AddToolTipTarget CtlName: {0}, isClientID: {1}",CtlName,isClientID ), PageTraceSwitch.Sw.Info);
                ToolTipManagerBottom.TargetControls.Add(CtlName,isClientID);
                return;
            }

            if ( ToolTipManager != null)
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage AddToolTipTarget CtlName: {0}, isClientID: {1}",CtlName,isClientID ), PageTraceSwitch.Sw.Info);
                ToolTipManager.TargetControls.Add(CtlName,isClientID);
            }
        }

        public void AddToolTipTarget(string CtlName,TootipPos Pos)
        {
            AddToolTipTarget(CtlName,false,Pos);
        }

        #endregion RadToolTipManager

        #region AjaxToolbox
        
        #region Ajax.Net

        public bool HasScriptManager
        {
            get
            {
                ScriptManager sman  = ScriptManager.GetCurrent(this);
                if ( sman != null )
                    return true;
                return false;
            }
        }

        public ScriptManager PageScriptManager
        {
            get
            {
                return ScriptManager.GetCurrent(this);
            }
        }

        public bool IsInAsyncPostBack
        {
            get
            {
                ScriptManager sman  = ScriptManager.GetCurrent(this);
                if ( sman != null )
                    return sman.IsInAsyncPostBack;
                return false;
            }
        }

        /// <summary>
        /// Do a redirect, if in Ajax callback uses AjaxManager to redirect due to IIS7 pb with Response.Redirect
        /// </summary>
        public void Redirect(string url,bool endResponse)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Redirect BEG url: '{0}', endResponse: {1}.", url,endResponse),PageTraceSwitch.Sw.Info);
            if ( IsInAsyncPostBack && ( AjaxManager != null ) )
            {
                if ( url.StartsWith("~/") )
                    url     =   ResolveClientUrl(url);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Redirect by AjaxManager url: {0}.",url),PageTraceSwitch.Sw.Info);
                try
                {
                    AjaxManager.Redirect(url);
                }
			    catch(System.Threading.ThreadAbortException) 
                {
                    throw;
                } 
                catch (Exception ex)
                {
                    if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage Redirect by Ajax ex: {0}", ex),PageTraceSwitch.Sw.Info);
                    Response.Redirect(url,endResponse);
                } 
                return;
            }
            Response.Redirect(url,endResponse);
        }

        #endregion Ajax.Net
        
        #region RadAjax.Net
        
        public bool HasAjaxManager
        {
            get
            {
                return ( AjaxManager != null );
            }
        }

        RadAjaxManager _AjaxManager =  null;
        public RadAjaxManager AjaxManager
        {
            get
            {
                if ( _AjaxManager == null )
                {
                    _AjaxManager    =   RadAjaxManager.GetCurrent(this);
                }
                return _AjaxManager;
            }
        }

        public void AddAjaxSetting(Control ajaxifiedControl,Control updatedControl)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( 
                    string.Format("[V]ADNPage AddAjaxSetting PageID: {0}, HasAjaxManager: {1}, ajaxifiedControl: {2}, updatedControl: {3}",
                new object[]{PageID,HasAjaxManager,ajaxifiedControl,updatedControl}),PageTraceSwitch.Sw.Info);
            if ( !HasAjaxManager )
                return;
            AjaxManager.AjaxSettings.AddAjaxSetting(ajaxifiedControl,updatedControl);
        }
        
        #endregion RadAjax.Net
        #endregion AjaxToolbox

        #region ValidationGroup
        
        public virtual string ValidationGroup
        {
            get
            {
                string validationGroup          =   (string)ViewState["ValidationGroup"];
                if (validationGroup != null)
                {
                    return validationGroup;
                }
                return string.Empty;
            }
            set
            {
                ViewState["ValidationGroup"]    =   value;
            }
        }

        internal virtual bool RequiresValidation()
		{
			return GetValidators(ValidationGroup).Count > 0;
		}
        
        internal virtual bool RequiresValidation(string validationGroup)
		{
			return GetValidators(validationGroup).Count > 0;
		}

        #endregion ValidationGroup

        #region EventCallBack

        public Dictionary<int,PortalModuleControl> LoadedModules   =   new Dictionary<int,PortalModuleControl>();

        internal PostBackOptions GetPostBackOptions(Control control, string argument, string validationGroup, string postBackUrl)
		{
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage GetPostBackOptions BEG argument: {0}, validationGroup: {1}, postBackUrl: {2}", argument, validationGroup,postBackUrl), PageTraceSwitch.Sw.Info);
			PostBackOptions options         =   new PostBackOptions(control, argument);
			options.ClientSubmit            =   true;
            bool reqVal                     =   RequiresValidation( validationGroup);
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage GetPostBackOptions RequiresValidation: {0}", reqVal), PageTraceSwitch.Sw.Info);
			if ( reqVal )
			{
				options.PerformValidation   =   true;
				options.ValidationGroup     =   validationGroup;
			}
			if (!string.IsNullOrEmpty(postBackUrl))
			{
				options.ActionUrl           =   postBackUrl;
			}
			return options;
		}

		protected virtual string GetPostbackEventReference(string arg)
		{
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage GetPostbackEventReference BEG arg: {0}", arg), PageTraceSwitch.Sw.Info);
			string eventReference   =   ClientScript.GetPostBackEventReference(GetPostBackOptions(this,arg,ValidationGroup,null));
			eventReference          =   eventReference.Replace("\"", "'");
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage GetPostbackEventReference BEG eventReference: {0}", eventReference), PageTraceSwitch.Sw.Info);
            return eventReference;
		}

        public virtual void RaisePostBackEvent(string eventArgument)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RaisePostBackEvent eventArgument: {0}", eventArgument.ToString()), PageTraceSwitch.Sw.Info);
        }

        #endregion EventCallBack

        #region license

        private AddonNice.Core.AddonNice _Adn;
        
        /// <summary>
        /// Check for AddonNice license
        /// To override in childs if we need totest another license
        /// </summary>
        protected virtual bool CheckLicense
        {
            get
            {
                if (_Adn == null)
                    _Adn = new AddonNice.Core.AddonNice();
                if (_Adn != null)
                    return _Adn.License.IsValid;
                return false;
            }
        }

        protected bool DoCheckLicense()
        {
            return CheckLicense;
        }
        
        
        /// <summary>
        /// Check for AddonNice license demo mode
        /// To override in childs if we need to test another license
        /// </summary>
        public virtual bool IsDemo
        {
            get
            {
                if (_Adn == null)
                    _Adn = new AddonNice.Core.AddonNice();
                if (_Adn != null)
                    return _Adn.DemoMode;
                return true;
            }
        }
        
        /// <summary>
        /// Get the extended info string from license
        /// </summary>
        public virtual string DemoInfo
        {
            get
            {
                if (_Adn == null)
                    _Adn = new AddonNice.Core.AddonNice();
                if (_Adn != null)
                    return _Adn.License.Info;
                return string.Empty;
            }
        }
        
        #endregion license
        
        #region Standard Page Controls
        		
		/// <summary>
		/// Avoid forbidden methods like FindControl in designMode
		/// </summary>
		protected bool IsDesignMode
		{
			get
			{
				return ( ((Site != null) && Site.DesignMode) || (HttpContext.Current == null) );
			}
		}
        
        /// <summary>
        /// Limit theme loading and slow methods and unecessary action 
        /// Redefine this to true for pages used as Temporary (like sending a file to client) and which don't need to load themes and other slowing down methods
        /// </summary>
        public virtual bool FastLoadPage
		{
			get
			{
				return false;
			}
		}

        /// <summary>
        /// Replacement for theme : we force the .NET2 theme from PortalSettings which take local custom theme or site theme
        /// </summary>
        public override string Theme
        {
            get
            {
                string strTm        =   base.Theme;
                if ( !FastLoadPage && string.IsNullOrEmpty(strTm))
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]ADNPage Theme GET not set, before call GetCurrentPageTheme.",PageTraceSwitch.Sw.Info);
                    string strTheme =   portalSettings.GetCurrentPageTheme();
                    if (!string.IsNullOrEmpty(strTheme))
                        base.Theme  =   strTheme;
                    strTm           =   base.Theme;
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Theme GET setting theme: {0}", strTheme),PageTraceSwitch.Sw.Info);
                }
                if (PageThemesTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Theme GET theme: '{0}'", strTm,PageThemesTrace.Sw.Info),PageThemesTrace.Sw.Info);
                return strTm;
            }
            set
            {
                if ( FastLoadPage || ( base.Theme == value ) )
                    return;
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Theme SET old theme: '{0}', new Theme: '{1}'", base.Theme,value),PageTraceSwitch.Sw.Info);
                base.Theme          =   value;
            }
        }

        
		/// <summary>
		/// Internal replacement for stylesheet theme set by OnPreInit
		/// </summary>
        public override string StyleSheetTheme
        {
            get
            {
                string strSts   =   string.Empty;
                if ( !FastLoadPage && ( portalSettings != null ) && portalSettings.UseStyleSheetTheme)
                {
                    if (!string.IsNullOrEmpty(base.StyleSheetTheme))
                        strSts  =   base.StyleSheetTheme;
                    else strSts =   portalSettings.CurrentPageTheme;
                }
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage StyleSheetTheme GET : {0}", strSts),PageTraceSwitch.Sw.Info);
                return strSts;
            }
        }

        
        /// <summary>
        /// Checks if monitoring is enabled in web.config and if the Monitor object has been correctly initialized during the application initialization
        /// </summary>
        public bool IsMonitoring
        {
            get
            {
                return ( Config.IsMonitoringEnabled && InitApplication.MonInitObject != null);
            }
        }

        public Control _GlobalPane  =   null;
        /// <summary>
        /// If the Page Contains panes, this is the control which contains the panes
        /// Set by the pane itself
        /// </summary>
        public virtual Control GlobalPane
        {
            get
            {
                return _GlobalPane;
            }
            set
            {
                _GlobalPane =   value;
            }
        }

        /// <summary>
        /// if the page contains Panes, try to find a Pane with the corresponding ID
        /// </summary>
        public virtual Control GetPane(string paneID)
        {
            if ( GlobalPane == null )
                return null;
            if ( (GlobalPane is AddonNicePanesBase) &&
                ((AddonNicePanesBase)GlobalPane).UsePanels )
            {
                switch (paneID)
                {
                    case StStr.leftPane:
                        return ((AddonNicePanesBase)GlobalPane).LeftPane.Controls[0];
                    case StStr.contentPane:
                        return ((AddonNicePanesBase)GlobalPane).ContentPane.Controls[0];
                    case StStr.rightPane:
                        return ((AddonNicePanesBase)GlobalPane).RightPane.Controls[0];
                }
            }
            return GlobalPane.FindControl(paneID);
        }


        protected virtual ImageButton NewImageButton(string btnID)
        {
            ImageButton btn     =   new ImageButton();
            btn.ID              =   btnID;
            return btn;
        }


        
        #endregion

        #region Extenders
        /*
            <cc1:ConfirmButtonExtender ID="RestoreBtn_ConfirmButtonExtender" runat="server" 
        ConfirmText="Confirm ?" Enabled="True" TargetControlID="RestoreBtn">
    </cc1:ConfirmButtonExtender>
        */
        protected bool HasCancelExtender   =   false;
        protected bool HasDeleteExtender   =   true;
        protected bool HasUpdateExtender   =   false;
        protected bool HasCustomExtender   =   false;


        #endregion extenders

        #region Client Confirm scripts

        bool _StatusScriptRegistered        =   false;
        public void RegisterStatusScript()
        {
            if ( _StatusScriptRegistered )
                return;
            string gPath                =   Path2.ToAbsolute(Config.PortalScriptsPath+"/ADNToStatus.js");
            string pPath                =   MapPath(gPath);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterStatusScript pPath: {0}.",pPath),PageTraceSwitch.Sw.Info);
            RegisterADNClientScriptInclude(GetType(), "ADNToStatus", gPath);
            if ( HasAjaxManager )
            {
                // We must execute this on end of page loading by browser
                string scrpt            =   "InitADNStatus();";
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterStatusScript ResponseScripts.Add script: {0}",scrpt),PageTraceSwitch.Sw.Info);
                AjaxManager.ResponseScripts.Add(scrpt);
                _StatusScriptRegistered =   true;
            }
        }

        public void RegisterClientConfirm()
        {
            bool async      =   IsInAsyncPostBack;
            if ( PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterClientConfirm() BEG AsyncPostBack: {0}, useRadConfirm: {1}", async,useRadConfirm),PageTraceSwitch.Sw.Info);
            if ( async )
                return;
            if ( useRadConfirm )
                    RegisterClientRadConfirm(GetType());
            else    RegisterClientConfirm(GetType());
        }

        public void RegisterClientConfirm(Type cs)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterClientConfirm BEG type: {0}, HasScriptManager: {1}.", cs,HasScriptManager),PageTraceSwitch.Sw.Info);
            // if PageScriptManager is not defined may be we came too early so position a flag to retry later
            if ( PageScriptManager == null )
            {
                shouldRegisterConfirm   =   true;
                return;
            }
            // Check to see if the startup script is already registered.
            Version v = Request.Browser.EcmaScriptVersion;
            if ((v.Major >= 1))
            {
                string scrpt            =   "clientConfirm(ajaxManId,msg, event, oWidth, oHeight, callerObj, oTitle){\nvar agree=confirm(txt); if (agree) return true; return false;}";
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptBlock(this,cs, "clientConfirm", scrpt, true);
                }
                else
                {
                    if (!IsPageClientScriptBlockRegistered(cs, "clientConfirm"))
                        RegisterPageClientScriptBlock(cs, "clientConfirm", scrpt, true);
                }
            }
        }

        bool RadConfirmRegistered   =   false;
        public void RegisterClientRadConfirm(Type cs)
        {
            bool hasScriptMan           =   HasScriptManager;
            bool hasAjax                =   (AjaxManager != null);
            if ( PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterClientRadConfirm BEG type: {0}, HasScriptManager: {1}, hasAjax: {2}, RadConfirmRegistered: {3}.", 
                    new object[]{cs,hasScriptMan,hasAjax,RadConfirmRegistered}),PageTraceSwitch.Sw.Info);
            if ( RadConfirmRegistered )
                return;
            // if PageScriptManager is not defined may be we came too early so position a flag to retry later
            if ( !hasScriptMan || !hasAjax )
            {
                shouldRegisterConfirm   =   true;
                return;
            }

            // Check to see if the startup script is already registered.
            Version v                   =   Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1  )
            {
                RadConfirmRegistered    =   true;
                ScriptReference rf      =   new ScriptReference(Config.PortalScriptsPath+"/TelerikConfirm.js");
                // FK4 rf.NotifyScriptLoaded   =   true;
                PageScriptManager.Scripts.Add(rf);
                // We must execute this on end of page loading by browser
                string scrpt            =   "ConfirmLoadHandler();";
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterClientRadConfirm ResponseScripts.Add script: {0}", scrpt), PageTraceSwitch.Sw.Info);
                AjaxManager.ResponseScripts.Add(scrpt);
            }
        }

        /// <summary>
		/// Set the button attributes to prompt user before doing a postback/callback. 
		/// </summary>
		public void setClientConfirmAttributes(WebControl Btn,string msg,string title)
		{
            bool isButton                   =   ( Btn is Button );
            
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage setClientConfirmAttributes WebControl BEG Btn.ID: {0}, isButton: {1}", Btn.ID,isButton), PageTraceSwitch.Sw.Info);
            RadAjaxManager ajm              =   AjaxManager;
            string ajmClientID              =   string.Empty;
            if ( ajm != null )
                ajmClientID                 =   ajm.ClientID;
            string js                       =   string.Format("return clientConfirm('{0}', '{1}', event, null, null,null,'{2}');",ajmClientID, msg, title);
            if ( isButton )
            {
                Button Btn2                 =   (Button)Btn;
                if ( !string.IsNullOrEmpty(Btn2.OnClientClick) )
                        Btn2.OnClientClick  =   js+Btn2.OnClientClick;
                else    Btn2.OnClientClick  =   js;
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage setClientConfirmAttributes Btn.OnClientClick: [{0}]", Btn2.OnClientClick), PageTraceSwitch.Sw.Info);
            }
            else
            {
                if ( Btn.Attributes["onclick"] != null )
                        Btn.Attributes["onclick"] = js;
                else    Btn.Attributes.Add("onclick",js);
            }
            RegisterClientConfirm();
		} 
        
		public void setClientConfirmAttributes(ModuleButton Btn,string msg,string title)
		{
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage setClientConfirmAttributes ModuleButton BEG Btn.ID: {0}", Btn.ID), PageTraceSwitch.Sw.Info);
            RadAjaxManager ajm              =   AjaxManager;
            string ajmClientID              =   string.Empty;
            if ( ajm != null )
                ajmClientID                 =   ajm.ClientID;
            string js                       =   string.Format("return clientConfirm('{0}', '{1}', event, null, null,null,'{2}');",ajmClientID, msg, title);
            if ( Btn.Attributes["onclick"] != null)
                 Btn.Attributes["onclick"] = js + Btn.Attributes["onclick"];
            else Btn.Attributes.Add("onclick",js);
            RegisterClientConfirm();
		} 

        #endregion Client Confirm scripts

        #region scripts management

        #region Scripts that are not involved in asynchronous postbak and that don't need to be included on each postback

        public bool IsPageClientScriptBlockRegistered(Type cs, string key)
        {
            return ClientScript.IsClientScriptBlockRegistered(cs, key);
        }
        public bool IsPageStartupScriptRegistered(Type cs, string key)
        {
            return ClientScript.IsStartupScriptRegistered(cs, key);
        }
        public bool IsPageClientScriptIncludeRegistered(Type cs, string key)
        {
            return ClientScript.IsClientScriptIncludeRegistered(cs, key);
        }

        
        public void RegisterPageArrayDeclaration(string arrayName, string arrayValue)
        {
            ClientScript.RegisterArrayDeclaration(arrayName,arrayValue);
        }
        
        public void RegisterPageClientScriptBlock(Type cs, string key, string src, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1)
            {
                if (!IsPageClientScriptBlockRegistered(cs, key))
                    ClientScript.RegisterClientScriptBlock(cs,key, src, addTags);
            }
        }
        public void RegisterPageClientScriptInclude(Type cs, string key, string filePath)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                if (!IsPageClientScriptIncludeRegistered(cs,key))
                    ClientScript.RegisterClientScriptInclude(cs, key, filePath);
            }
        }
        public void RegisterPageStartupScript(Type cs, string key, string scrpt, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if (v.Major >= 1)
            {
                if (!IsPageStartupScriptRegistered(cs, key))
                    ClientScript.RegisterStartupScript(cs, key, scrpt, addTags);
            }
        }
        #endregion Scripts that are not involved in asynchroneous postback and that don't need to be included on each postback

        #region Scripts that need to be included on each asynchronous postback

        public void RegisterAsyncArrayDeclaration(string arrayName, string arrayValue)
        {
            if (HasScriptManager)
            {
                ScriptManager.RegisterArrayDeclaration(this,arrayName,arrayValue);
            }
        }

        public void RegisterAsyncArrayDeclaration(Control ctl,string arrayName, string arrayValue)
        {
            if (HasScriptManager)
            {
                ScriptManager.RegisterArrayDeclaration(ctl,arrayName,arrayValue);
            }
        }

        public void RegisterAsyncClientScriptBlock(Type cs, string key, string src, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1)
            {
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptBlock(this,cs,key, src, addTags);
                }
            }
        }

        public void RegisterAsyncClientScriptInclude(Type cs, string key, string filePath)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                if ( HasScriptManager )
                {
                    ScriptManager.RegisterClientScriptInclude(this,cs, key,filePath);
                }
            }
        }
        public void RegisterAsyncStartupScript(Type cs, string key, string scrpt, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if (v.Major >= 1)
            {
                if (HasScriptManager)
                {
                    ScriptManager.RegisterStartupScript(this,cs, key, scrpt, addTags);
                }
            }
        }

        public void RegisterAsyncClientScriptBlock(Control ctl,Type cs, string key, string src, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1)
            {
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptBlock(ctl,cs,key, src, addTags);
                }
            }
        }

        public void RegisterAsyncClientScriptInclude(Control ctl,Type cs, string key, string filePath)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                if ( HasScriptManager )
                {
                    ScriptManager.RegisterClientScriptInclude(ctl,cs, key,filePath);
                }
            }
        }
        public void RegisterAsyncStartupScript(Control ctl,Type cs, string key, string scrpt, bool addTags)
        {
            Version v = Request.Browser.EcmaScriptVersion;
            if (v.Major >= 1)
            {
                if (HasScriptManager)
                {
                    ScriptManager.RegisterStartupScript(ctl,cs, key, scrpt, addTags);
                }
            }
        }
        #endregion Scripts that need to be included on each asynchronous postback

        #region Scripts checking scriptManager presence

        public void RegisterADNArrayDeclaration(string arrayName, string arrayValue)
        {
            if (HasScriptManager)
            {
                ScriptManager.RegisterArrayDeclaration(this,arrayName,arrayValue);
            }
            else ClientScript.RegisterArrayDeclaration(arrayName,arrayValue);
        }

        public void RegisterADNArrayDeclaration(Control ctl,string arrayName, string arrayValue)
        {
            if (HasScriptManager)
            {
                ScriptManager.RegisterArrayDeclaration(ctl,arrayName,arrayValue);
            }
            else ClientScript.RegisterArrayDeclaration(arrayName,arrayValue);
        }

        public bool RegisterADNClientScriptBlock(Type cs, string key, string src, bool addTags)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterADNClientScriptBlock BEG key: {0}, src: {1}, addTags: {2}", key,src,addTags), PageTraceSwitch.Sw.Info);
            bool    Ok  =   false;
            Version v   =   Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptBlock(this, cs, key, src, addTags);
                }
                else
                {
                    if (!IsPageClientScriptBlockRegistered(cs,key))
                        ClientScript.RegisterClientScriptBlock(cs, key, src, addTags);
                }
            }
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RegisterADNClientScriptBlock END Ok: {0}",Ok), PageTraceSwitch.Sw.Info);
            return Ok;
        }

        public bool RegisterADNClientScriptInclude(string key, string fileUrl)
        {
            return RegisterADNClientScriptInclude(GetType(),key,fileUrl);
        }

        public bool RegisterADNClientScriptInclude(Type cs, string key, string fileUrl)
        {
            bool    Ok  =   false;
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptInclude(this, cs, key, fileUrl);
                }
                else
                {
                    if (!IsPageClientScriptIncludeRegistered(cs, key))
                        ClientScript.RegisterClientScriptInclude(cs, key, fileUrl);
                }
            }
            return Ok;
        }

        public bool RegisterADNStartupScript(Type cs, string key, string scrpt, bool addTags)
        {
            bool    Ok  =   false;
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if (HasScriptManager)
                {
                    ScriptManager.RegisterStartupScript(this, cs, key, scrpt, addTags);
                }
                else
                {
                    if (!IsPageStartupScriptRegistered(cs, key))
                        ClientScript.RegisterStartupScript(cs, key, scrpt, addTags);
                }
            }
            return Ok;
        }

        public bool RegisterADNClientScriptBlock(Control ctl,Type cs, string key, string src, bool addTags)
        {
            bool    Ok  =   false;
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if (HasScriptManager)
                {
                    ScriptManager.RegisterClientScriptBlock(ctl,cs,key, src, addTags);
                }
                else ClientScript.RegisterClientScriptBlock(cs,key, src, addTags);
            }
            return Ok;
        }

        public bool RegisterADNClientScriptInclude(Control ctl,Type cs, string key, string filePath)
        {
            bool    Ok  =   false;
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if ( HasScriptManager )
                {
                    ScriptManager.RegisterClientScriptInclude(ctl,cs, key,filePath);
                }
                else ClientScript.RegisterClientScriptInclude(cs, key,filePath);
            }
            return Ok;
        }

        public bool RegisterADNStartupScript(Control ctl,Type cs, string key, string scrpt, bool addTags)
        {
            bool    Ok  =   false;
            Version v = Request.Browser.EcmaScriptVersion;
            if ( v.Major >= 1 )
            {
                Ok      =   true;
                if (HasScriptManager)
                {
                    ScriptManager.RegisterStartupScript(ctl, cs, key, scrpt, addTags);
                }
                else
                {
                    if (!IsPageStartupScriptRegistered(cs, key))
                        ClientScript.RegisterStartupScript(cs, key, scrpt, addTags);
                }
            }
            return Ok;
        }

        #endregion Scripts checking scriptManager presence

        #region Loading of portalModules

        /// <summary>
        /// Customized LoadControl method that takes care to call Page_PreInit for the module, allowing skins adaptation
        /// before including the portal Module in the Page controls collection
        /// </summary>
        public virtual PortalModuleControl LoadPortalModule(string controlPath, int wPortalID, ModuleConfiguration wModuleConfiguration,bool readOnly)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage LoadPortalModule controlPath: {0},wPortalID : {1}, readOnly: {2}.", 
                    controlPath,wPortalID,readOnly),ModuleTraceSwitch.Sw.Info);
            bool moduleConfOk                   =   wModuleConfiguration != null;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage LoadPortalModule ModuleConfiguration != null: {0}.", moduleConfOk),ModuleTraceSwitch.Sw.Info);

            PortalModuleControl portalModule = null;
            try
            {
                    portalModule    = (PortalModuleControl)LoadControl(controlPath);
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage LoadPortalModule controlPath : {0}, ex : {1}", controlPath, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }

            portalModule.PortalID                   =   wPortalID;
            int idxNm                               =   0;
            string ModName                          =   "Mdl";

            // installs the module config if exists
            if ( moduleConfOk )
            {
                portalModule.ModuleBaseConfiguration    =   wModuleConfiguration;
                idxNm                                   =   wModuleConfiguration.ModuleID;
                ModName                                 =   wModuleConfiguration.ModuleTitle.Substring(0,Math.Min(wModuleConfiguration.ModuleTitle.Length,5)).Replace(' ','_');
            }

            // CS 8/5/07 :we check the control has a unique id, needed to add ajax support
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage LoadPortalModule before change ID: [{0}].", portalModule.ID),ModuleTraceSwitch.Sw.Info);
            // to avoid duplicates IDs
            string strPortalModuleID            =   string.Format("M_{0}_{1}", ModName, idxNm);
            portalModule.ID                     =   strPortalModuleID;
            portalModule.ReadOnly               =   readOnly;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage LoadPortalModule after change ID: [{0}], idxNm: {1}.", portalModule.ID, idxNm),ModuleTraceSwitch.Sw.Info);

            // CS 12/2/7: this will allow all themes for portalmodules controls : for dynamically loaded modules
            // skins names must be set before the theme being set in the Page
            try
            {
                portalModule.Page_PreInit(this, new EventArgs());
                // Add it to loaded modules
                LoadedModules.Add(idxNm,portalModule);
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage LoadPortalModule controlPath : {0}, ex : {1}", controlPath, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            return portalModule;
        }
        
        #endregion Loading of portalModules

        #endregion scripts management

        #region return url management

        const string SessionReturnUrl   =   "ReturnUrl";
        object LockPage                 =   new object();
        

        /// <summary>
        /// Stack which contains the last calling url, must be filled before called a page we expect return from
        /// Especially usefull for modules properties
        /// </summary>
        public Stack<string> ReturnUrlStk
        {
            get
            {
                Stack<string> stk   =   GetReturnStk(PageID);
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ReturnUrlStk GET PageID: '{0}', Count: {1}.",PageID,stk.Count), PageTraceSwitch.Sw.Info);
                return stk;
            }
        }

        public Stack<string> GetReturnStk(int PgId)
        {
            object ob                               =   Session[SessionReturnUrl];
            if ( ob == null )
            {
                lock(Session.SyncRoot)
                {
                    ob                              =   Session[SessionReturnUrl];
                    if ( ob == null )
                    {
                        ob                          =   new SortedList<int,Stack<string>>();
                        Session[SessionReturnUrl]   =   ob;
                    }
                }
            }
            SortedList<int,Stack<string>> lst       =   (SortedList<int,Stack<string>>)ob;
            if ( !lst.ContainsKey(PgId) )
            {
                lock(LockPage)
                {
                    lst.Add(PgId,new Stack<string>());
                }
            }

            return lst[PgId];
        }

        public void ForceReturnUrl4Page(int PgId,string RetUrl)
        {
            Stack<string> stk   =   GetReturnStk(PgId);
            stk.Push(RetUrl);
        }

        /// <summary>
        /// GET tries first to extract its value from viewstate using the urlreferrer property
        /// If empty, it gets it from session based storage for current pageID
        /// Return is based first on viewstate, then on session values
        /// We must pop from stack in any case to be sure to get last return value in place
        /// Beware GET will pop the element from stack, so don't call it twice...
        /// When needed to check value on stack, call peek on ReturnUrlStk
        /// </summary>
        public virtual string ReturnUrl
        {
            get
            {
                string str              =   UrlReferrer;
                string str2             =   string.Empty;
                Stack<string> stk       =   ReturnUrlStk;
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ReturnUrl GET UrlReferrer: '{0}', ReturnUrlStk.Count: {1}.",str,stk.Count), PageTraceSwitch.Sw.Info);
                // we must pop and return after
                if (stk.Count > 0)
                    str2                =   stk.Pop();
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ReturnUrl GET Stack.Url: '{0}', Count: {1}.",str2,stk.Count), PageTraceSwitch.Sw.Info);
                if ( str != string.Empty )
                    return str;
                if ( str2 == string.Empty ) // default to home page
                    return HttpUrlBuilder.BuildUrl();
                return str2;
            }
            set
            {
                Stack<string> stk   =   ReturnUrlStk;
                // clean the stack ( no Lifo list is available in .net ....)
                // we keep only last fives pushed elements
                int n               =   stk.Count;
                if ( n > 10)
                {
                    string[] ar     =   stk.ToArray();
                    stk.Clear();
                    for ( int i= 0; i < 5 ; i++ )
                        stk.Push(ar[i]);
                }
                // Don't push same url
                if (( stk.Count == 0 ) || (stk.Peek() != value ))
                    stk.Push(value);
               
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ReturnUrl SET: '{0}', Count: {1}.",value,stk.Count), PageTraceSwitch.Sw.Info);
            }
        }
        
        /// <summary>
        /// If urlRef contains a property window, we are coming back from a property window and we don't store it
        /// Else we store it :
        /// a) in viewstate: it is the reference value
        /// b) in a dedicated stack for this PageID: it will be used when viewstate is empty due to a call to property window
        /// </summary>
        public virtual void SaveUrlReferrer()
        {
            if (Request.UrlReferrer == null)
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage SaveUrlReferrer UrlReferrer Null for type: {0}, PageId: {1}.", this,PageID), PageTraceSwitch.Sw.Info);
                return;
            }
            string str          =   Request.UrlReferrer.ToString();
            string modulePath   =   Config.ModulesPath.TrimStart(new char[]{'~','/'});
            if ( (str == string.Empty ) || 
                ( str.IndexOf(modulePath) != -1 ) ||
                ( str.IndexOf(Config.ModuleSettingsPage,StringComparison.InvariantCultureIgnoreCase) != -1 ) ||
                ( str.IndexOf(Config.PageLayoutPage,StringComparison.InvariantCultureIgnoreCase) != -1 ) ||
                ( str.IndexOf(Config.ModulePropertyPage,StringComparison.InvariantCultureIgnoreCase) != -1 ) ||
                ( str.IndexOf(Config.PortalLogonDirectory+"/",StringComparison.InvariantCultureIgnoreCase) != -1 ) || // here don't allow storing pages from logon
                ( str.IndexOf(Config.ModuleCustomPropertyPage,StringComparison.InvariantCultureIgnoreCase) != -1 )  ||
                ( str.IndexOf(portalSettings.DefaultEditProfilePageUrl,StringComparison.InvariantCultureIgnoreCase) != -1 ) // don't go ack to edit profile
                )
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage SaveUrlReferrer UrlReferrer not stored, contains propertyPage: '{0}', PageId: {1}.", str,PageID), PageTraceSwitch.Sw.Info);
                return;
            }
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage SaveUrlReferrer UrlReferrer: '{0}'.",str), PageTraceSwitch.Sw.Info);
            UrlReferrer     =   str;
            ReturnUrl       =   str;

        }
        
        #endregion return url management

        #region Standard Control events override

        /// <summary>
        /// .Net 2: we must set themes and skins in OnPreInit
        /// For dynamics controls used with loadcontrol, skinID must be set before inclusion in the control collection
        /// </summary>
        protected override void OnPreInit(EventArgs e)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreInit BEG FastLoadPage: {0}.",FastLoadPage),PageTraceSwitch.Sw.Info);
            // Register the page in context for ErrorHandler
            Context.Items["ADNPage"]    =   this;
            // Apply new theme
            string tm                   =   base.Theme;
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreInit tm: '{0}'.", tm),PageTraceSwitch.Sw.Info);
            if ( !FastLoadPage && string.IsNullOrEmpty(tm) )
            {
                // try to get it from custom theme
                string strTheme         =   string.Empty;
                // if no settings or settings identical to activePage, get them from portal
                int pgId                =   PageID;
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreInit PageID: {0}, ActivePageSettings null: {1}", pgId, (portalSettings.ActivePageSettings == null)),PageTraceSwitch.Sw.Info);
                if ( ( pgId == portalSettings.ActivePageSettings.PageID ) || (_Settings == null) )
                    strTheme            =   portalSettings.GetCurrentPageTheme();
                else
                {
                    if (Settings.ContainsKeyNotEmpty(StStr.PageCustomTheme))
                    {
                        try
                        {
                            strTheme    =   Settings[StStr.PageCustomTheme].Value.Trim();
                            if ( PageTraceSwitch.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreInit local Theme: {0}", strTheme),PageTraceSwitch.Sw.Info);
                        }
                        catch (Exception ex)
                        {
                            if ( PageTraceSwitch.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage OnPreInit ex: {0}", ex),PageTraceSwitch.Sw.Info);
                            throw;
                        }
                    }
                    else 
                    {
                        strTheme        =   portalSettings.CurrentTheme;
                        // no custom theme
                        if ( PageTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreInit no customTheme using portal CurrentTheme: {0}", strTheme),PageTraceSwitch.Sw.Info);
                    }
                }
                if (!string.IsNullOrEmpty(strTheme))
                    base.Theme          =   strTheme;
                if (PageTraceSwitch.Sw.TraceInfo)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[I]ADNPage OnPreInit Installing Theme: [{0}]", Theme),PageTraceSwitch.Sw.Info);
            }
            base.OnPreInit(e);
            if (PageTraceSwitch.Sw.TraceInfo)
                Trace2.WriteLine("[I]ADNPage OnPreInit END.",PageTraceSwitch.Sw.Info);
        }

        protected override void InitializeCulture()
        {
           if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage InitializeCulture BEG Culture: {0}, UICulture: {1}.",Culture,UICulture),PageTraceSwitch.Sw.Info);
           base.InitializeCulture();
           if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage InitializeCulture END Culture: {0}, UICulture: {1}.",Culture,UICulture),PageTraceSwitch.Sw.Info);
        }



        /// <summary>
        /// Handles the OnInit event at Page level<br/>
        /// Performs OnInit events that are common to all Pages<br/>
        /// Can be overridden
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage OnInit BEG.",PageTraceSwitch.Sw.Info);
            if ( !FastLoadPage )
            {
                LoadSettings();
                ModuleGuidInCookie();
            }

            base.OnInit(e);

            if ( !FastLoadPage )
            {
                // register the global js script for all pages if exists
                string gPath        =   Path2.ToAbsolute(Config.PortalScriptsPath+"/ADNGlobal.js");
                string pPath        =   MapPath(gPath);
                if ( File.Exists(pPath))
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnInit pPath: {0}, Registering: {1}",pPath, gPath),PageTraceSwitch.Sw.Info);
                    RegisterADNClientScriptInclude(GetType(), "ADNGlobal", gPath);
                }
            }

            // Check License on end of init
            bool ok =   DoCheckLicense();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnInit END License: {0}, Demo: {1}", ok, IsDemo),PageTraceSwitch.Sw.Info);
        }

        private const string TelerikKey             = "Telerik.Web.UI.Key";        
        
        /// <summary>
		/// Handles OnLoad event at Page level<br/>
		/// Performs OnLoad actions that are common to all Pages.
		/// </summary>
		protected override void OnLoad(EventArgs e) 
		{
            // Telerik dedicated version
            Application[TelerikKey]                 =  "Addon Nice v1"; 
            Boolean FormExist                       =   ( Form != null );
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnLoad BEG IsPostBack: {0}, IsInAsyncPostBack: {1}, Form null: {2}, Form.Action: '{3}'.",
                    new object[]{IsPostBack,IsInAsyncPostBack, !FormExist ,FormExist ? Form.Action:string.Empty}),PageTraceSwitch.Sw.Info);
            
            // Pb with FireFox cache which could stop ajax.net on back or refresh
            /* CS removed 15/01/10
            if (Request.Browser.MSDomVersion.Major == 0) // Non IE Browser?)   
            {       
                Response.Cache.SetNoStore(); // No client side cashing for non IE browsers   
            }
            */
            // slow see url rewritter object ob   =   Request.ServerVariables["HTTP_XW_ORIGINAL_URL"];
            if ( !FastLoadPage )
            {
                object ob           =   HttpContext.Current.Items["HTTP_XW_ORIGINAL_URL"];
                if ( ( ob != null ) && FormExist )
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnLoad HTTP_XW_ORIGINAL_URL: {0}.",ob),PageTraceSwitch.Sw.Info);
                    Form.Action     =   (string)ob;
                }

                // Stores referring URL in viewstate
                // Push this address as a return address
                if (!IsPostBack && FormExist )
                {
                    SaveUrlReferrer();
                }
    			
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnLoad shouldRegisterConfirm: {0}.", shouldRegisterConfirm),PageTraceSwitch.Sw.Info);
                if ( FormExist && shouldRegisterConfirm)
                {
                    RegisterClientConfirm();
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnLoad after registerClientConfirm RadConfirmRegistered: {0}.", RadConfirmRegistered ),PageTraceSwitch.Sw.Info);
                }
            }
            base.OnLoad(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage OnLoad END.",PageTraceSwitch.Sw.Info);
        }

#if DEBUG
        protected override object SaveViewState()
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ADNPage SaveViewState BEG.",PageTraceSwitch.Sw.Info);
            object o    = base.SaveViewState();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ADNPage SaveViewState END.",PageTraceSwitch.Sw.Info);
            return o;
        }
        protected override void LoadViewState(object savedState)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ADNPage LoadViewState BEG.",PageTraceSwitch.Sw.Info);
            base.LoadViewState(savedState);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ADNPage LoadViewState END.",PageTraceSwitch.Sw.Info);
        }
        protected override void OnPreRenderComplete(EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ADNPage OnPreRenderComplete BEG.",PageTraceSwitch.Sw.Info);
            base.OnPreRenderComplete(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage OnPreRenderComplete END.",PageTraceSwitch.Sw.Info);
        }
#endif // DEBUG
        
        protected override void OnPreRender(EventArgs e)
        {
            Boolean FormExist   =   ( Form != null );
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage OnPreRender BEG IsPostBack: {0}, IsInAsyncPostBack: {1}, Form.Action: '{2}'.",
                    IsPostBack,IsInAsyncPostBack,FormExist ? Form.Action: string.Empty),PageTraceSwitch.Sw.Info);
            if ( !FastLoadPage )
            {
                BuildHtmlHead();
                if ( portalSettings.CustomSettings[StStr.SiteSettingsCombineCss].ToBool() )
                    CombineCssLinks();
            }
            base.OnPreRender(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage OnPreRender END.",PageTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// If enabled, replace all css links in header by a call to adncss handler to load only one file
        /// </summary>
        private void CombineCssLinks()
        {
            string theme                        =   this.Theme;
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage CombineCssLinks BEG Theme: {0}.",theme),PageTraceSwitch.Sw.Info);
            var hasTheme                        =   false;
            foreach ( HtmlLink link in Page.Header.Controls.OfType<HtmlLink>().ToList() )
            {
                AttributeCollection attributes  =   link.Attributes;
                string href                     =   attributes["href"];
                string type                     =   attributes["type"];
                bool isCss                      =   type.EqualsIgnoreCase("text/css");
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage CombineCssLinks href: {0}, type: {1}, isCss: {2}.",href,type,isCss),PageTraceSwitch.Sw.Info);
                if ( isCss && href.StartsWith("~") )
                {
                    string url                  =   ResolveUrl(href);
                    string file                 =   System.IO.Path.GetFileName(href);
                    string location             =   Server.UrlEncode(href);
                    if ( url.ContainsIgnoreCase(string.Format("App_Themes/{0}",theme)) )
                    {
                        if ( !hasTheme )
                        {
                            string query        =   string.Format("adncss.axd?t={0}",theme);
                            if ( portalSettings.CustomSettings[StStr.SiteSettingsCacheCssOnClient].ToBool() )
                                query           +=  "&c=1";
                            if ( portalSettings.CustomSettings[StStr.SiteSettingsCompressCss].ToBool() )
                                query           +=  "&p=1";

                            attributes["href"]  =   url.Replace(file,query);
                            hasTheme            =   true;
                        }
                        else
                        {
                            // We've already injected a query for this theme; remove link                        
                            link.Parent.Controls.Remove(link);
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// with Telerik: in some occasions (?) Render is called twice
        /// </summary>
        protected override void Render(HtmlTextWriter writer)
        {
            Boolean FormExist   =   ( Form != null );
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Render BEG IsPostBack: {0}, IsInAsyncPostBack: {1}, Form.Action: '{2}'.",
                    IsPostBack,IsInAsyncPostBack,FormExist ? Form.Action: string.Empty),PageTraceSwitch.Sw.Info);
            try
            {
                base.Render(writer);
			}
			catch (Exception ex)
			{
				if ( PageTraceSwitch.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage Render ex :{0}", ex),PageTraceSwitch.Sw.Info);
				throw;
			}
			if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage Render END.",PageTraceSwitch.Sw.Info);
        }

        #endregion Standart Control events override

		#region Properties (Portal)
		private PortalSettings _portalSettings;
        
		/// <summary>
		/// Stores current portal settings 
		/// </summary>
		public PortalSettings portalSettings
		{
			get
			{
				if(_portalSettings == null)
				{
					// Obtain PortalSettings from Current Context
					if (!IsDesignMode)
						_portalSettings = (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
				}
				return _portalSettings;
			}
			set
			{
				_portalSettings = value;
			}
		}
		#endregion
		
		#region Properties (Page)
		
        /// <summary>
		/// List of CSS files to be applied to this page
		/// </summary>
		private Hashtable _cssFileList = new Hashtable(3);
		public bool IsCssFileRegistered(string key)
		{
			if ( _cssFileList.ContainsKey(key.ToLower()) )
				return true;
			return false;
		}
		public void RegisterCssFile(string key, string file)
		{
			_cssFileList.Add(key.ToLower(), file);
		}
		public void ClearCssFileList()
		{
			_cssFileList.Clear();
		}

        
        private string _PageTitle	=	string.Empty; 
		
        /// <summary>
		/// Try to find if any localized title exists
		/// </summary>
		public string PageTitle 
		{
			get
			{
				if ( string.IsNullOrEmpty(_PageTitle) )
				{
					if (IsDesignMode )
                        return string.Empty;
					{
                    
                    CultureInfo ci              =   portalSettings.PortalContentLanguage;
				    string currentLanguage      =   ci.Name.ToUpper().Replace('-', '_');
				    string currentNLanguage     =   string.Empty;
                    bool IsNeutralCulture       =   ci.IsNeutralCulture;
                    if ( !IsNeutralCulture )
                    {
                        ci                      =   ci.Parent;
			            currentNLanguage        =   ci.Name.ToUpper().Replace('-', '_');
                    }

                    if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentLanguage))
                        _PageTitle              =   portalSettings.ActivePageSettings.Settings[currentLanguage].Value;
                    else if ( !IsNeutralCulture &&  portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentNLanguage))
                        _PageTitle              =   portalSettings.ActivePageSettings.Settings[currentNLanguage].Value;
                    // no get the default page title if not empty (should not!)
                    else if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageTitle) )
                        _PageTitle              =   portalSettings.ActivePageSettings.Settings[StStr.PageTitle].Value;
                    // Security default portal value
                    else if ( portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageTitle) )
                        _PageTitle              =   portalSettings.CustomSettings[StStr.SiteSettingsPageTitle].Value;
                    // Security default portal value
                    else _PageTitle             =   portalSettings.PortalTitle;
					}				
				}
				return _PageTitle;
			}
			set
			{
				_PageTitle = value;
			}
		}

        private string _PageKeyPhrase	=	string.Empty;
        /// <summary>
		/// Stores current Page Key Phrase
		/// </summary>
		public string PageKeyPhrase
		{
			get
			{
                if ( DesignMode )
                    return StStr.PageKeyPhrase;
				
                if ( !string.IsNullOrEmpty(_PageKeyPhrase) )
					return _PageKeyPhrase;
                CultureInfo ci                  =   portalSettings.PortalContentLanguage;
			    string currentLanguage          =   StStr.PageKeyPhrase_under+ ci.Name.ToUpper().Replace('-', '_');
			    string currentNLanguage         =   string.Empty;
                bool IsNeutralCulture           =   ci.IsNeutralCulture;
                if ( !IsNeutralCulture )
                {
                    ci                          =   ci.Parent;
		            currentNLanguage            =   StStr.PageKeyPhrase_under+ ci.Name.ToUpper().Replace('-', '_');
                }

                if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentLanguage))
                    _PageKeyPhrase              =   portalSettings.ActivePageSettings.Settings[currentLanguage].Value;
                else if ( !IsNeutralCulture &&  portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentNLanguage))
                    _PageKeyPhrase       =   portalSettings.ActivePageSettings.Settings[currentNLanguage].Value;
                else if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageKeyPhrase))
					_PageKeyPhrase              =   portalSettings.ActivePageSettings.Settings[StStr.PageKeyPhrase].ToString();
			    else if ( portalSettings.CustomSettings.ContainsKey(StStr.SiteSettingsPageKeyPhrase) )
				    _PageKeyPhrase              =   portalSettings.CustomSettings[StStr.SiteSettingsPageKeyPhrase].ToString();						

				return _PageKeyPhrase;
			}
		}

        private string _PageMetaKeyWords	=	string.Empty;
		/// <summary>
		/// "keywords" meta element
		/// </summary>
		public string PageMetaKeyWords
		{
			get
			{
                if ( string.IsNullOrEmpty(_PageMetaKeyWords) )
				{
                    if ( IsDesignMode )
                        return string.Empty;

                    CultureInfo ci              =   portalSettings.PortalContentLanguage;
				    string currentLanguage      =   StStr.PageMetaKeyWords_under+ ci.Name.ToUpper().Replace('-', '_');
				    string currentNLanguage     =   string.Empty;
                    bool IsNeutralCulture       =   ci.IsNeutralCulture;
                    if ( !IsNeutralCulture )
                    {
                        ci                      =   ci.Parent;
			            currentNLanguage        =   StStr.PageMetaKeyWords_under+ ci.Name.ToUpper().Replace('-', '_');
                    }

                    if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentLanguage))
                        _PageMetaKeyWords       =   portalSettings.ActivePageSettings.Settings[currentLanguage].Value;
                    else if ( !IsNeutralCulture &&  portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentNLanguage))
                        _PageMetaKeyWords       =   portalSettings.ActivePageSettings.Settings[currentNLanguage].Value;
                    else if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageMetaKeyWords))
                        _PageMetaKeyWords       =   portalSettings.ActivePageSettings.Settings[StStr.PageMetaKeyWords].Value;
                    else if ( portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaKeywords) )
                        _PageMetaKeyWords       =   portalSettings.CustomSettings[StStr.SiteSettingsPageMetaKeywords].Value;
					else
                        _PageMetaKeyWords = string.Empty;
				}
                return _PageMetaKeyWords;
			}
		}

        private string _PageMetaDescription = string.Empty;
        /// <summary>
        /// "description" meta element
        /// </summary>
        public string PageMetaDescription
        {
            get
            {
                if (string.IsNullOrEmpty(_PageMetaDescription))
                {
                    if ( IsDesignMode )
                        return string.Empty;
                    CultureInfo ci              =   portalSettings.PortalContentLanguage;
				    string currentLanguage      =   StStr.PageMetaDescription_under+ ci.Name.ToUpper().Replace('-', '_');
				    string currentNLanguage     =   string.Empty;
                    bool IsNeutralCulture       =   ci.IsNeutralCulture;
                    if ( !IsNeutralCulture )
                    {
                        ci                      =   ci.Parent;
			            currentNLanguage        =   StStr.PageMetaDescription_under+ ci.Name.ToUpper().Replace('-', '_');
                    }

                    if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentLanguage))
                        _PageMetaDescription    =   portalSettings.ActivePageSettings.Settings[currentLanguage].Value;
                    else if ( !IsNeutralCulture &&  portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(currentNLanguage))
                        _PageMetaDescription    =   portalSettings.ActivePageSettings.Settings[currentNLanguage].Value;
                    else if ( portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageMetaDescription))
                        _PageMetaDescription    =   portalSettings.ActivePageSettings.Settings[StStr.PageMetaDescription].Value;
                    else if (portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaDescription))
                        _PageMetaDescription    =   portalSettings.CustomSettings[StStr.SiteSettingsPageMetaDescription].Value;
                    else
                        _PageMetaDescription    =   string.Empty;
                }
                return _PageMetaDescription;
            }
        }
        

        private string _IE8BrowserMode = string.Empty;
		/// <summary>
		/// New IE 8 browser mode: meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" 
		/// </summary>
		public string IE8BrowserMode
		{
			get
			{
                if (string.IsNullOrEmpty(_IE8BrowserMode))
				{
                    if (!IsDesignMode && portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.IE8BrowserMode))
                        _IE8BrowserMode = portalSettings.ActivePageSettings.Settings[StStr.IE8BrowserMode].Value;
                    else if (!IsDesignMode && portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsIE8BrowserMode) )
                        _IE8BrowserMode = portalSettings.CustomSettings[StStr.SiteSettingsIE8BrowserMode].Value;
					else
                        _IE8BrowserMode = string.Empty;
				}
                return _IE8BrowserMode;
			}
		}
    
        private string _PageMetaRobots = string.Empty;
		/// <summary>
		/// "robots" meta element
		/// </summary>
		public string PageMetaRobots
		{
			get
			{
                if (string.IsNullOrEmpty(_PageMetaRobots))
				{
                    if (!IsDesignMode && portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageMetaRobots))
                        _PageMetaRobots = portalSettings.ActivePageSettings.Settings[StStr.PageMetaRobots].Value;
                    else if (!IsDesignMode && portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaRobots) )
                        _PageMetaRobots = portalSettings.CustomSettings[StStr.SiteSettingsPageMetaRobots].Value;
					else
                        _PageMetaRobots = string.Empty;
				}
                return _PageMetaRobots;
			}
		}

        private string _PageMetaExpires = string.Empty;
		/// <summary>
		/// "expires" meta element
		/// </summary>
        public string PageMetaExpires
		{
			get
			{
                if (string.IsNullOrEmpty(_PageMetaExpires))
				{
                    if (!IsDesignMode && portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageMetaExpires))
                        _PageMetaExpires = portalSettings.ActivePageSettings.Settings[StStr.PageMetaExpires].Value;
                    else if (!IsDesignMode && portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaExpires) )
                        _PageMetaExpires = portalSettings.CustomSettings[StStr.SiteSettingsPageMetaExpires].Value;
					else
                        _PageMetaExpires = string.Empty;
				}
                return _PageMetaExpires;
			}
		}

        private string _PageMetaRefresh = string.Empty;
        /// <summary>
        /// "refresh" meta element
        /// </summary>
        public string PageMetaRefresh
        {
            get
            {
                if (string.IsNullOrEmpty(_PageMetaRefresh))
                {
                    if (!IsDesignMode && portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageMetaRefresh))
                        _PageMetaRefresh = portalSettings.ActivePageSettings.Settings[StStr.PageMetaRefresh].Value;
                    else if (!IsDesignMode && portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaRefresh))
                        _PageMetaRefresh = portalSettings.CustomSettings[StStr.SiteSettingsPageMetaRefresh].Value;
                    else
                        _PageMetaRefresh = string.Empty;
                }
                return _PageMetaRefresh;
            }
        }


        private string _PageEncoding = string.Empty;
        /// <summary>
        /// "encoding" meta element
        /// </summary>
        public string PageEncoding
        {
            get
            {
                if (string.IsNullOrEmpty(_PageEncoding))
                {
                    if (!IsDesignMode && portalSettings.ActivePageSettings.Settings.ContainsKeyNotEmpty(StStr.PageEncoding))
                        _PageEncoding = portalSettings.ActivePageSettings.Settings[StStr.PageEncoding].Value;
                    else if (!IsDesignMode && portalSettings.CustomSettings.ContainsKeyNotEmpty(StStr.SiteSettingsPageMetaEncoding))
                        _PageEncoding = portalSettings.CustomSettings[StStr.SiteSettingsPageMetaEncoding].Value;
                    else
                        _PageEncoding = string.Empty;
                }
                return _PageEncoding;
            }
        }

        protected bool DefaultUrlReferrerToPageID  =   false;

        /// <summary>
		/// Referrer URL is by decreasing order of choice: 
        /// 1) previous page from request.referrer 
        /// 2) depending the Flag DefaultUrlReferrerToPageID
        ///     2a ) this page (or calling ADNPage ) using pageID 
        ///     2b ) string.empty -> change to adapt staking of urlreferrer, previously home page
		/// </summary>
		protected virtual string UrlReferrer
		{
			get
			{
                string str		=   string.Empty;
                if (ViewState[StStr.strUrlReferrer] != null)
                {
                    str         =   (string)ViewState[StStr.strUrlReferrer];
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage UrlReferrer GET from ViewState url: {0}", str), PageTraceSwitch.Sw.Info);
                }
                else
                {
                    if (DefaultUrlReferrerToPageID)
                        str     =   HttpUrlBuilder.BuildUrl(PageID);
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage UrlReferrer GET DefaultUrlReferrerToPageID: {0}, url: '{1}'", DefaultUrlReferrerToPageID, str), PageTraceSwitch.Sw.Info);
                }
                return str;
			}
			set
			{
				ViewState[StStr.strUrlReferrer] = value;
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage UrlReferrer SET: '{0}'", value),PageTraceSwitch.Sw.Info);
            }
		}


		#endregion

		#region Settings (Pages)
		private int _pageID = StStr.PageIDNotAssigned ;

		/// <summary>
		/// Stores current linked page ID if applicable
		/// </summary>
		public virtual int PageID
		{
			get
			{
				if (_pageID == StStr.PageIDNotAssigned )
				{
					// Determine PageID if specified
					if ( !IsDesignMode )
					{
                        // Extract PageId from querystring using pageid then tabid ( compat old code)
                        try
                        {
                            _pageID     =   Portal.PageID;
                        }
                        catch (Exception ex)
                        {
                            if (PageTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage PageID GET ex: {0}", ex),PageTraceSwitch.Sw.Info);
                        }
						// CS 28/8/04
                        if ( (_pageID == StStr.PageIDNotAssigned) 
                            && ( portalSettings != null ) 
                            && ( portalSettings.ActivePageSettings != null ) )
                        {
                            _pageID     =   portalSettings.ActivePageSettings.PageID;
                            if ( PageTraceSwitch.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage PageID GET not found in query set from ActivePageSettings.PageID: {0}", _pageID),PageTraceSwitch.Sw.Info);
                        }
					}
				}
				return _pageID;
			}		
		}

        /// <summary>
        /// Reset any value cached locally or in cache for this page
        /// </summary>
        public void ResetSettings(bool resetCache)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ResetSettings BEG PageID: '{0}'", PageID),PageTraceSwitch.Sw.Info);
            Settings    =   null;
		    if ( portalSettings != null && 
                portalSettings.ActivePageSettings != null &&
                portalSettings.ActivePageSettings.PageID == PageID )
                portalSettings.ActivePageSettings.Reset(resetCache);
            if ( resetCache && CurrentCache.Exists(Key.TabSettings(PageID)))
                    CurrentCache.Remove(Key.TabSettings(PageID));
            // Clear url builder elements
            HttpUrlBuilder.Clear(PageID);
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage ResetSettings END PageID: '{0}'", PageID),PageTraceSwitch.Sw.Info);
        }

        private SettingsDictionary _Settings    =   null;
		/// <summary>
		/// Dictionary of SettingItems for
        /// - current Page when Page is a totally database generated Page composed of modules
        /// - calling Page when the page is a Property or complementary Page called from a module in the original Page
		/// </summary>
        public SettingsDictionary Settings
		{
			get
			{
				if( _Settings == null )
				{
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Settings GET is null, getting from PortalSettings for PageID: '{0}'", PageID),PageTraceSwitch.Sw.Info);
					// Get settings from the database
                    if ( PageID > 0 )
                    {
                        if ( PageID != portalSettings.ActivePageSettings.PageID )
                        {
                            if (PageTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Settings GET PageID: '{0}' != portalSettings.ActivePageSettings.PageID: '{1}'", PageID,portalSettings.ActivePageSettings.PageID),PageTraceSwitch.Sw.Info);
                            _Settings   =   portalSettings.ActivePageSettings.GetPageCustomSettings(PageID);
                        }
                        else _Settings  =   portalSettings.ActivePageSettings.Settings;
                    }
                    else
                    {
                        // Or provides an empty SettingsDictionary 
                        _Settings       =   new SettingsDictionary();
                        if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine("[V]ADNPage Settings GET PageID == 0 creating empty dictionary.",PageTraceSwitch.Sw.Info);
                    }
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Settings GET PageID: {0}, pageSettings.Count: '{1}'", PageID, _Settings.Count),PageTraceSwitch.Sw.Info);
                return _Settings;
			}
            set
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                {
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Settings SET PageID: {0}, value is null: {1}", PageID, value == null), PageTraceSwitch.Sw.Info);
                    if ( value != null )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Settings SET PageID: {0}, pageSettings.Count: '{1}'.", PageID, _Settings.Count), PageTraceSwitch.Sw.Info);
                }
                _Settings = value;
            }
		}

		#endregion Settings (Pages)

		#region Methods
		
        /// <summary>
		/// Virtual LoadSettings method to be redefined in child object to complete additionnal load task
		/// </summary>
		protected virtual void LoadSettings()
		{}

		/// <summary>
		/// Redirect back to the referring page
		/// </summary>
		public void RedirectBackToReferringPage()
		{
//			Response.Redirect throws a ThreadAbortException to make it work, 
//			which is handled by the ASP.NET runtime. 
//			By catching an Exception (not a specialized exception, just the
//			base exception class), you end up catching the ThreadAbortException which is
//			always thrown by the Response.Redirect method. Normally, the ASP.NET runtime
//			catches this exception and handles it itself, hence your page never really
//			realized an exception occurred. So by catching this exception, you stop the
//			normal order of events that happen when redirecting.
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RedirectBackToReferringPage UrlReferrer: {0}", UrlReferrer),PageTraceSwitch.Sw.Info);
            try 
            { 
                // try using session based stack of urls
                string redirectUrl  =   ReturnUrl;
                if ( redirectUrl == string.Empty )
                    redirectUrl     =   UrlReferrer;
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage RedirectBackToReferringPage redirectUrl: '{0}'",redirectUrl),PageTraceSwitch.Sw.Info);
                Redirect(redirectUrl,true);
            }
			catch(System.Threading.ThreadAbortException) 
            {
                throw;
            } 
            catch (Exception ex)
            {
                if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage RedirectBackToReferringPage UrlReferrer: {0}, ex: {1}", UrlReferrer,ex),PageTraceSwitch.Sw.Info);
                throw;
            } //Do nothing it is normal
        }

		protected string _popUpOptions = "toolbar=1,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=800,height=600,screenX=15,screenY=15,top=15,left=15";
        public virtual string GetPopupCommand()
        {
            return GetPopupCommand(_popUpOptions);
        }

        /// <summary>
		/// Builds Javascript popup command
		/// </summary>
		/// <returns>popup command as a string</returns>
		public virtual string GetPopupCommand(string popUpOptions)
		{
            string gPath        =   Path2.ToAbsolute(Config.PortalScriptsPath+"/popup.js");
            RegisterADNClientScriptInclude("adn_popup", gPath);
			// build the popup command
		    return string.Format("link_popup(this, '{0}');return false;",popUpOptions);
		}

		/// <summary>
		/// Builds the HTML head element 
		/// </summary>
		protected virtual void BuildHtmlHead()
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead BEG Title: {0}.", PageTitle),PageTraceSwitch.Sw.Info);
            
            // ADD THE PAGE TITLE
			Header.Title            =   PageTitle;

            // ADD THE META TAGS

            // New IE 8 browser mode <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead Request.Browser.Type: '{0}', Request.Browser.Version: '{1}', IE8BrowserMode: '{2}'.",
                    Request.Browser.Type,Request.Browser.Version,IE8BrowserMode),PageTraceSwitch.Sw.Info);
            HtmlMeta hm             =   null;
            if ( Request.Browser.Type.ToUpper().IndexOf("IE") > -1 )
            {
                double iev          =   0d;
                try
                {
                    iev             =   Double.Parse(Request.Browser.Version, System.Globalization.CultureInfo.InvariantCulture);
                }
                catch(Exception ex)
                {
                    if ( PageTraceSwitch.Sw.TraceError || GlobalTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage Request.Browser.Version: '{0}', ex: {2}.",
                            Request.Browser.Version,ex), ( PageTraceSwitch.Sw.TraceError ) ? PageTraceSwitch.Sw.Info:GlobalTraceSwitch.Sw.Info);
                    if ( Request.Browser.Version.IndexOf("8") > -1 )
                        iev         =   8d;
                }
                if ( ( iev >= 8.00) && !string.IsNullOrEmpty(IE8BrowserMode) )
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead IE8 detected IE8BrowserMode: IE={0}",IE8BrowserMode),PageTraceSwitch.Sw.Info);
                    hm              =   new HtmlMeta();
                    hm.HttpEquiv    =   "X-UA-Compatible";
                    hm.Content      =   string.Format("IE={0}",IE8BrowserMode);
                    if ( Header.Controls.Count > 0 )
                         Header.Controls.AddAt(1,hm);
                    else Header.Controls.Add(hm);
                }
            }
            
            //Addon Nice is the generator
            hm                      =   new HtmlMeta();
            hm.Name                 =   "generator";
            hm.Content              =   "AddonNice - http://www.addonnice.com";
            Header.Controls.Add(hm);

            // keywords
            if ( !string.IsNullOrEmpty(PageMetaKeyWords) )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageMetaKeyWords: {0}", PageMetaKeyWords),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.Name             =   "keywords";
                hm.Content          =   PageMetaKeyWords;
                Header.Controls.Add(hm);
            }

			// description
			if ( !string.IsNullOrEmpty(PageMetaDescription) )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageMetaDescription: {0}", PageMetaDescription),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.Name             =   "description";
                hm.Content          =   PageMetaDescription;
                Header.Controls.Add(hm);
            }

			// robots
            if ( !string.IsNullOrEmpty(PageMetaRobots) )
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageMetaRobots: {0}", PageMetaRobots),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.Name             =   "robots";
                hm.Content          =   PageMetaRobots;
                Header.Controls.Add(hm);
            }
            // expires
            if (!string.IsNullOrEmpty(PageMetaExpires))
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageMetaExpires: {0}", PageMetaExpires),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.Name             =   "expires";
                hm.Content          =   PageMetaExpires;
                Header.Controls.Add(hm);
            }
            // Refresh ->in content "seconds;url=new_url"
            if (!string.IsNullOrEmpty(PageMetaRefresh))
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageMetaRefresh: {0}", PageMetaRefresh),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.HttpEquiv        =  "refresh";
                hm.Content          =   PageMetaRefresh;
                Header.Controls.Add(hm);
            }

            // encoding
            if (!string.IsNullOrEmpty(PageEncoding))
            {
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead PageEncoding: {0}", PageEncoding),PageTraceSwitch.Sw.Info);
                hm                  =   new HtmlMeta();
                hm.HttpEquiv        =  "Content-Type";
                hm.Content          =   PageEncoding;
                Header.Controls.Add(hm);
            }


			// ADD SHORTCUT ICON <LINK>
            HtmlLink myHtmlLink     =   new HtmlLink();
            myHtmlLink.Href         =   string.Format("{0}/portalicon.ico", Path2.WebPathCombine(Path2.ApplicationRoot, portalSettings.PortalPath));
            myHtmlLink.Attributes.Add("rel", "SHORTCUT ICON");
            // Add the HtmlLink to the Head section of the page.
            Header.Controls.Add(myHtmlLink);

            // ADD THE CSS <LINK> ELEMENT(S), Warning this should be done with themes
            foreach (string _cssFile in _cssFileList.Values)
            {
                myHtmlLink          =   new HtmlLink();
                myHtmlLink.Href     =   string.Format("{0}", _cssFile);
                myHtmlLink.Attributes.Add("rel", "sytlesheet");
                myHtmlLink.Attributes.Add("type", "text/css");
                // Add the HtmlLink to the Head section of the page.
                Header.Controls.Add(myHtmlLink);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNPage BuildHtmlHead Added css file: {0}", _cssFile),PageTraceSwitch.Sw.Info);
            }
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ADNPage BuildHtmlHead END.",PageTraceSwitch.Sw.Info);
		}

		#endregion
		
		#region Security access

        /// <summary>
		///  This array is override for edit and view pages
		///  with the guids allowed to access.
		/// </summary>
		protected virtual ArrayList AllowedModules
		{
			get
			{
				return null;
			}
		}

		/// <summary>
		///  Every guid module in tab is set in cookie.
		///  This method is overriden in edit & view controls for reading the cookie
		///  and allowing or denieding access to edit or view module.
		/// </summary>
		protected virtual void ModuleGuidInCookie()
		{
			Guid guid           =   Guid.Empty;

			ModulesDB mdb		=   new ModulesDB();
			StringBuilder sb	=	new StringBuilder();

			if (portalSettings.ActivePageSettings.Modules.Count > 0)
			{
				foreach (ModuleConfiguration ms in portalSettings.ActivePageSettings.Modules)
				{
					try
					{
						guid    =   mdb.GetModuleGuid(ms.ModuleID);
					}
					catch(Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNPage.ModuleGuidInCookie ModuleID : {0}, ex : {1}",ms.ModuleID,ex),PageTraceSwitch.Sw.Info);
						continue;
					}
					if (guid != Guid.Empty) 
						sb.AppendFormat("{0}@",guid.ToString().ToUpper());
				}
			}
			HttpCookie cookie	=	new HttpCookie(StStr.strSecurityCookieName, sb.ToString());
			DateTime time		=	DateTime.Now;
			TimeSpan span		=	new TimeSpan (0, 2, 0, 0, 0); // 120 minutes to expire
			cookie.Expires		=	time.Add (span);
			base.Response.AppendCookie (cookie);
		}

		#endregion

		#region Query extension CS 10/2004

		public event QueryDateChangedEventHandler QueryDateChangedEvent;

		protected virtual void OnQueryDateChanged(QueryDateChangedEventArgs e) 
		{
			if ( QueryDateChangedEvent != null )
				QueryDateChangedEvent(e);
		}
		
		public bool ExistQueryDate
		{
			get
			{
                if (IsDesignMode)
                    return false;
				object ob	=	ViewState["QueryDate"]; // Should be a cookie
				if ( ob == null || !(ob is DateTime) )
				{
					string strDate	=	string.Empty;
					if ( Request.Cookies["QueryDateModule"] != null )
					{
						strDate = Request.Cookies["QueryDateModule"].Value;
						try
						{
							DateTime dt	= DateTime.Parse(strDate,CultureInfo.InvariantCulture);
							ViewState["QueryDate"]	=	dt;
							return true;
						}
						catch(Exception ex)
						{
							if (PageTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Parse failed for Date : '{0}', ex : {1}",strDate,ex),PageTraceSwitch.Sw.Info);
						}
					}
				return false;
				}
			return true;
			}
		}

		public DateTime QueryDate
		{
			get
			{
                if ( IsDesignMode )
                    return DateTime.MinValue;
				object ob	=	ViewState["QueryDate"];
				if ( ob == null || !(ob is DateTime))
				{
					string strDate	=	string.Empty;
					if ( Request.Cookies["QueryDateModule"] != null )
					{
						strDate = Request.Cookies["QueryDateModule"].Value;
						try
						{
							DateTime dt	= DateTime.Parse(strDate,CultureInfo.InvariantCulture);
							ViewState["QueryDate"]	=	dt;
							return dt;
						}
						catch(Exception ex)
						{
							if (PageTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Parse failed for Date : '{0}', ex : {1}",strDate,ex),PageTraceSwitch.Sw.Info);
						}
					}
					return DateTime.Now;
				}
				return (DateTime)ob;
			}
			set
			{
				QueryDateChangedEventArgs e	=	new QueryDateChangedEventArgs(QueryDate,value);
				ViewState["QueryDate"]		=	value;
				// We insert a cookie with date value
				HttpCookie cookie			=	new HttpCookie ("QueryDateModule", value.ToShortDateString());
				TimeSpan span				=	new TimeSpan (0, 2, 0, 0, 0); // 120 minutes to expire
				cookie.Expires				=	DateTime.Now.Add (span);
				base.Response.AppendCookie(cookie);

				OnQueryDateChanged(e);
			}
		}

		public event SortOrderChangedEventHandler SortOrderChangedEvent;

		protected virtual void OnSortOrderChanged(SortOrderChangedEventArgs e) 
		{
			if ( SortOrderChangedEvent != null )
				SortOrderChangedEvent(e);
		}

		public string SortOrder
		{
			get
			{
				object ob	=	ViewState["SortOrder"];
				if ( ob == null )
					return string.Empty;
				return (string)ob;
			}
			set
			{
				if ( SortOrder == value )
					return;
				SortOrderChangedEventArgs e	=	new SortOrderChangedEventArgs(SortOrder,value);
				ViewState["SortOrder"]	=	value;
				if ( base.IsPostBack )
					OnSortOrderChanged(e);
			}
		}

		public string SortOrderList
		{
			get
			{
				object ob	=	ViewState["SortOrderList"];
				if ( ob == null )
					return string.Empty;
				return (string)ob;
			}
			set
			{
				ViewState["SortOrderList"]	=	value;
			}
		}


		public event FilterChangedEventHandler FilterChangedEvent;

		protected virtual void OnFilterChanged(FilterChangedEventArgs e) 
		{
			if ( FilterChangedEvent != null )
				FilterChangedEvent(e);
		}
		public string Filter
		{
			get
			{
				object ob	=	ViewState["Filter"];
				if ( ob == null )
					return string.Empty;
				return (string)ob;
			}
			set
			{
				if ( Filter == value )
					return;
				FilterChangedEventArgs e	=	new FilterChangedEventArgs(Filter,value);
				ViewState["Filter"]	=	value;
				if ( base.IsPostBack )
					OnFilterChanged(e);
			}
		}

		public event PageSizeChangedEventHandler PageSizeChangedEvent;

		protected virtual void OnPageSizeChanged(PageSizeChangedEventArgs e) 
		{
			if ( PageSizeChangedEvent != null )
				PageSizeChangedEvent(e);
		}
		public virtual int PageSize
		{
			get
			{
				object ob	=	ViewState["PageSize"];
				if ( ob == null )
					return 0;
				return (int)ob;
			}
			set
			{
				if ( PageSize == value )
					return;
				PageSizeChangedEventArgs e	=	new PageSizeChangedEventArgs(PageSize,value);
				ViewState["PageSize"]	=	value;
				if ( base.IsPostBack )
					OnPageSizeChanged(e);
			}
		}
		public event SortDirectionChangedEventHandler SortDirectionChangedEvent;

		protected virtual void OnSortDirectionChanged(SortDirectionChangedEventArgs e) 
		{
			if ( SortDirectionChangedEvent != null )
				SortDirectionChangedEvent(e);
		}
		public virtual string SortDirection
		{
			get
			{
				object ob	=	ViewState["SortDirection"];
				if ( ob == null )
					return string.Empty;
				return (string)ob;
			}
			set
			{
				if ( SortDirection == value )
					return;
				SortDirectionChangedEventArgs e	=	new SortDirectionChangedEventArgs(SortDirection,value);
				ViewState["SortDirection"]	=	value;
				if ( base.IsPostBack )
					OnSortDirectionChanged(e);
			}
		}

		#endregion 
	}
}